package ua.com.common.STIntegration;

import java.io.File;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.support.ApplicationObjectSupport;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

import com.github.mustachejava.DefaultMustacheFactory;
import com.github.mustachejava.Mustache;
import com.github.mustachejava.MustacheFactory;

@Component
public class TemplateMustacheDAO  extends ApplicationObjectSupport implements InitializingBean{
	// FIXME: this
	private final boolean isDebug = false;
	
	private static final Logger logger = Logger.getLogger(TemplateMustacheDAO.class);
	
	Map<String,Mustache> all = new HashMap<String,Mustache>();
	private MustacheFactory mf = new DefaultMustacheFactory();
	
	// change this
	private static final String templateSubFolder = "templates/";
	// not this
	private String pathToTemplates;
	
	
	public void save(String name, String mustacheStr) {
	   	Mustache mustache = mf.compile(new StringReader(mustacheStr),name);
		this.save(name, mustache);		
	}
	
	public void save(String name, Mustache mustache) {
		logger.info("saving: <"+ name+"> template ");
		all.put(name, mustache);		
	}

	public Mustache get(String viewName) {
		return all.get(viewName);
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		populateTemplates();
	}
	
	private void populateTemplates() throws Exception {
 		pathToTemplates = getApplicationContext().getResource(".").getFile().getAbsolutePath()+"/"+templateSubFolder;

 		
		// 1 - load templates from files
 		File folder = new File(pathToTemplates);
 		File[] listOfFiles = folder.listFiles();
 		if(listOfFiles==null){
 			return; // io exception (unexist path from temp directory) - nothing to do here
 		}
 		
 		String templateName;
 		for (int i = 0; i < listOfFiles.length; i++){
 		   if (listOfFiles[i].isFile()) { 
 		   templateName = listOfFiles[i].getName(); 
 		       if (templateName.endsWith(".st") || templateName.endsWith(".ST")){
 		    	templateName = templateName.substring(0, templateName.length()-3);// remove extension
 		   		String html = FileUtils.readFileToString(listOfFiles[i]);
 		   		this.save(templateName, html);
 		        }
 		     }
 		  }
		
	}
	
	{

		if(isDebug){
			new Timer().scheduleAtFixedRate(new TimerTask() {
				@Override
				public void run() {
					try {
						populateTemplates();
						
						// while(true){ populateTemplates(); } memory ok
						
					} catch (Exception e) {
						e.printStackTrace();
					}
					
				}
			} , new Date(new Date().getTime()+2000),5000);

		}
	}

}
